const WxUtil = require('../../../utils/WxUtil.js')

//闲聊发问地址
const askApi = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat";
//发问语音识别地址
const askVoice2TextApi = "https://api.ai.qq.com/fcgi-bin/aai/aai_asr";

const app = getApp();
Page({

  data: {
    j: 1,//帧动画初始图片
    isSpeaking: false,
    voices: [],
    voiceFilePath: null,
    targetText: ""
  },

  //聊天，向机器人发问
  chat_ask(question) {
    let that = this;

    let time = new Date().getTime();
    let app_id = app.globalData.aiAppId;
    let time_stamp = parseInt(new Date().getTime() / 1000);
    let nonce_str = WxUtil.getRandStr();
    let session = app.globalData.openid.substring(0, 6) + time;
    question = WxUtil.textHandle(question);

    let params = {
      nonce_str: nonce_str,
      question: question,
      time_stamp: time_stamp,
      session: session,
      app_id: app_id
    }

    let sign = WxUtil.getReqSign(params);
    params.sign = sign;
    console.info("====params======");
    console.info(params);

    wx.request({
      url: askApi,
      method: 'post',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          targetText: res.data.data.answer,
        });

        wx.showToast({
          title: "[]"+res.data.data.answer,
        })
      },
      fail: function (error) {
        console.error(error)
      }
    })
  },

  onLoad: function () {
    
  },
  //手指按下
  touchdown: function () {
    var _this = this;
    speaking.call(this);
    this.setData({
      voiceFilePath: null,
      isSpeaking: true
    });
    //开始录音
    wx.startRecord({
      success: function (res) {
        //临时路径,下次进入小程序时无法正常使用
        var tempFilePath = res.tempFilePath
        console.log("tempFilePath: " + tempFilePath)
        //_this.setData({ voiceFilePath: tempFilePath});
        //_this.voice2text(tempFilePath);


        //持久保存
        wx.saveFile({
          tempFilePath: tempFilePath,
          success: function (res) {
            //持久路径
            //本地文件存储的大小限制为 100M
            var savedFilePath = res.savedFilePath;
            console.log("savedFilePath: " + savedFilePath);

            _this.setData({ voiceFilePath: savedFilePath });
            _this.voice2text(savedFilePath);
            //var voice = { filePath: savedFilePath, createTime:new Date()};
            //_this.setData({ voiceFilePath: savedFilePath, voiceCreateTime: new Date() });
          }
        })



       
      },
      fail: function (res) {
        //录音失败
        wx.showModal({
          title: '提示',
          content: '录音的姿势不对!',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              return
            }
          }
        })
      }
    })
  },
  //手指抬起
  touchup: function () {
    console.log("手指抬起了...")
    this.setData({
      isSpeaking: false,
    })
    clearInterval(this.timer)
    wx.stopRecord()
  },

  //语音识别
  voice2text:function(voicePath)
  {
    
    let that = this;
    console.info("voicePath=="+voicePath);
    let speech = wx.getFileSystemManager().readFileSync(voicePath, 'base64') 

    let params = {
      app_id: app.globalData.aiAppId,
      time_stamp: parseInt(new Date().getTime() / 1000),
      nonce_str: WxUtil.getRandStr(),
      format: 2,
      speech: speech,
      rate: 8000
    }

    let sign = WxUtil.getReqSign(params);
    params.sign = sign;
   
    wx.request({
      url: askVoice2TextApi,
      method: 'post',
      data: params,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.info("====识别出的文字====");
        console.info(res.data.data.text);
        let askText = "不好意思，没有听清楚";
        if(0==res.data.ret)
        {
          askText = res.data.data.text;
        }

        that.chat_ask(askText);
      },
      fail: function (error) {
        console.error(error)
      }
    })
    
  },

  //点击播放录音
  gotoPlay: function (e) {
    //var filePath = e.currentTarget.dataset.key;
    var filePath = this.data.voiceFilePath;
    console.info("gotoPlay filePath==" + filePath);
    wx.playVoice({
      filePath: filePath,
      success: function () {

      }
    });
  },

})

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}